package proc

import (
	"common"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"utils"
)

type UserProc struct {
}

func (this *UserProc) Login(userId int, userPwd string) (err error) {

	conn, err := net.Dial("tcp", "localhost:8888")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()
	fmt.Println("connect server success...")

	user := common.User{
		UserId:  userId,
		UserPwd: userPwd,
	}

	// 序列化 user
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 构建Message
	var mes common.Message
	mes.Type = common.LoginType
	mes.Data = string(data)

	ut := &utils.Utils{
		Conn: conn,
	}
	// send message
	fmt.Println("client start send message....")
	err = ut.WriteMes(&mes)

	// read message
	mes, err = ut.ReadMes()
	var res common.Res

	if err = json.Unmarshal([]byte(mes.Data), &res); err != nil {
		return err
	}

	if res.Code == common.Success {
		// 修改 curUser
		curUser.Conn = conn
		curUser.UserId = userId

		// 显示在线用户
		fmt.Println("return, 在线用户如下：")
		for _, val := range res.Users {
			if val == userId {
				continue
			}
			us := &common.User {
				UserId: userId,
				UserStatus: common.Online,
			}
			onlineUser[val] = us
			fmt.Print(val, "\t")
		}


		// 处理登录后服务端数据
		go ProcessServerMes(conn)
		// 显示二级菜单
		ShowMenu()
	} else {
		err = errors.New(res.Err)
	}
	return

}

func (this *UserProc) Register(userId int, userName, userPwd string) (err error) {
	conn, err := net.Dial("tcp", "localhost:8888")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer conn.Close()
	fmt.Println("connect server success...")

	user := common.User{
		UserId: userId,
		UserName: userName,
		UserPwd: userPwd,
	}

	// 序列化 user
	data, err := json.Marshal(user)
	if err != nil {
		fmt.Println("client json user err", err)
		return
	}

	// 构建Message
	var mes common.Message
	mes.Type = common.REGISTERTYPE
	mes.Data = string(data)

	ut := &utils.Utils{
		Conn: conn,
	}

	// send message
	fmt.Println("client send mes....")
	if err = ut.WriteMes(&mes); err != nil {
		fmt.Println("client send mes fail, err=", err)
		return
	}

	// read message
	mes, err = ut.ReadMes()
	if err != nil {
		fmt.Println("client read mes err=", err)
		return
	}
	var res common.Res

	if err = json.Unmarshal([]byte(mes.Data), &res); err != nil {
		fmt.Println("client unmarshal res err=",err)
		return err
	}
	if res.Code == common.RegisterError {
		err = common.ERROR_USER_EXISTS
	}
	return
}
